package com.ruoyi.thirdpart.service.impl;

import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerInfoService;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.market.domain.ConfigProgram;
import com.ruoyi.market.service.IConfigMessageService;
import com.ruoyi.market.service.IConfigProgramService;
import com.ruoyi.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.thirdpart.service.IWechatService;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序注册 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class WechatServiceImpl implements IWechatService
{

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private IConfigProgramService configProgramService;

    // 微信小程序注册
    @Override
    public JSONObject code2Session(String jsCode, String appId){

        String appSecret = "";
        // if(appId == null || appId.equals("")){
        //    appId = wxConfig.getAppId();
        //    appSecret = wxConfig.getAppSecret();
        // }else{
        //    appSecret = appInfoMapper.findAppSecret(appId);
        // }
        String url = new StringBuilder()
                .append("https://api.weixin.qq.com/sns/jscode2session?appid=")
                .append(appId)
                .append("&secret=")
                .append(appSecret)
                .append("&js_code=")
                .append(jsCode)
                .append("&grant_type=authorization_code").toString();

        JSONObject result = HttpUtils.doGet(url, null);
        String openid = result.getString("openid");
        String errcode = result.getString("errcode");
        System.out.println("code2Session result data ===> " + JSON.toJSONString(result));
        if (StringUtils.isEmpty(openid)) {
            if ("40029".equals(errcode)) {
                throw new ServiceException("code无效,错误码：40029");
            } else if ("45011".equals(errcode)) {
                throw new ServiceException("频率限制，每个用户每分钟100次,错误码：45011");
            } else if ("-101222100".equals(errcode)) {
                throw new ServiceException("请检查appid和appsecret是否正确,请检查ide上创建工程用的appid是否正确,错误码：-101222100");
            } else if ("-2100".equals(errcode)) {
                throw new ServiceException("请检查appid和appsecret是否正确,请检查ide上创建工程用的appid是否正确,错误码：-2100");
            } else if ("-1".equals(errcode)) {
                throw new ServiceException("系统繁忙，此时请开发者稍候再试,错误码：-1");
            } else if (!"0".equals(errcode)) {
                throw new ServiceException(result.getString("errmsg"));
            }
            throw new ServiceException("请求微信接口失败");
        }
        return result;
    }

    // 通过code换取网页授权access_token   https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
    @Override
    public String oauth2(String code, String shopId, String inviteId){
        ConfigProgram sysConfigProgram = configProgramService.selectConfigProgramByShopId(shopId);
        String secret = sysConfigProgram.getOfficialSecret();
        String appId = sysConfigProgram.getOfficialAppId();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + secret +
                "&code=" + code +
                "&grant_type=authorization_code";
        Map<String, String> requestObject1 = new HashMap<String, String>();
        JSONObject resultObject = HttpUtils.doGet(url, requestObject1);
        String openid = resultObject.getString("openid");
        String access_token = resultObject.getString("access_token");
        if(StringUtils.isEmpty(openid)){
            throw new ServiceException("错误：code已过期/已使用，请关闭页面重新打开");
        }
        CustomerUser user = customerUserService.selectUserByOpenId(openid);
        if(StringUtils.isNull(user)){
            // 不存在 先注册
            CustomerUser customerUser = new CustomerUser();
            customerUser.setUserName(openid);
            customerUser.setNickName(openid);
            customerUser.setOpenId(openid);
            customerUser.setShopId(shopId);
            customerUser.setAppId(appId);
            if(StringUtils.isNotEmpty(inviteId)){
                CustomerUser inviteUser = customerUserService.selectUserById(Long.valueOf(inviteId));
                if(StringUtils.isNotNull(inviteUser)){
                    customerUser.setInviteId(Long.valueOf(inviteId));
                }
            }
            customerUserService.insertUser(customerUser);
            snsUserinfo(access_token, openid, appId);
        }
        String token = customerInfoService.loginByOpenId(openid);
        return token;
    }

    // 拉取用户信息(需scope为 snsapi_userinfo)  https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
    public CustomerUser snsUserinfo(String access_token, String openid, String appId){
        String url = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        Map<String, String> requestObject1 = new HashMap<String, String>();
        JSONObject resultObject = HttpUtils.doGet(url, requestObject1);
        CustomerUser user = updateUserCenter(resultObject, appId);
        return user;
    }

    // 注册中心
    public CustomerUser updateUserCenter(JSONObject resultObject, String appId){
        String openid = resultObject.getString("openid");
        String nickname = resultObject.getString("nickname");
        String sex = resultObject.getString("sex");
        String headimgurl = resultObject.getString("headimgurl");
        String unionid = resultObject.getString("unionid");
        String province = resultObject.getString("province");
        String city = resultObject.getString("city");
        String country = resultObject.getString("country");
        CustomerUser user = customerUserService.selectUserByOpenId(openid);
        user.setUserName(openid);
        user.setNickName(decodeNickName(nickname));
        user.setSex(sex);
        user.setAvatar(headimgurl);
        user.setUnionId(unionid);
        user.setAddress(country + '-' + province + '-' + city);
        user.setOpenId(openid);
        user.setAppId(appId);
        customerUserService.updateUser(user);
        return user;
    }

    // 微信的名称乱码处理
    public static String decodeNickName(String nickName){
        try {
            return new String(nickName.getBytes("ISO-8859-1"), "UTF-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return nickName;
        }
    }
}
